<?php



/**
 * Deze versie van print_r returnt de waarde met de <pre> tag eromheen
 * @pararm	Mixed		$mData			Waarde die getoond moet worden (hoeft geen array te zijn!)
 * @return	String						Uitleg over hoe de variabele eruit ziet
 */
function sprint_r($mData, $bWith_pre = true)
{
	$sValues = '';
	
	switch (strtolower(gettype($mData)))
	{
		case "array":
			$sValues = print_r($mData, true);
			break;
		
		case "object":
			if (method_exists($mData, 'dump'))
				$sValues = $mData->dump();
			else
				$sValues = var_export($mData, true);
			
			break;
			
		default:
			ob_start();
			var_dump($mData);
			$sValues = ob_get_contents();
			ob_end_clean();
			break;
	}
	
	return $bWith_pre ? '<pre>'.$sValues.'</pre>' : $sValues;
}


/**
 * Case-insensitive explode. Gekopieert van php.net comment: http://nl3.php.net/manual/en/function.explode.php#58959
 * @param	String		$sSeperator		de tekst waardoor gedeeld moet worden
 * @param	String		$sString		de tekst die gedeeld moet worden
 * @return	Array						gesplitste delen
 */
function explodei ($sSeperator, &$sString)
{
	$sSeperator_l = strtolower($sSeperator);
	return explode($sSeperator_l,  str_ireplace($sSeperator, $sSeperator_l, $sString));
}


/**
 * Deze functie bestaat pas vanaf php 5.1.0 Dus voor lagere versies gebruiken we een eigen functie
 * De code is gekopieert van http://nl3.php.net/manual/en/function.htmlspecialchars-decode.php#54760
 */
if (!function_exists('htmlspecialchars_decode'))
{
	function htmlspecialchars_decode ($str, $quote_style = ENT_COMPAT) {
		return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
	}
}


/**
 * De functie zorgt ervoor dat een URL voldoet aan de voorwaarden van het W3C.
 * @param	string		$sUrl		URL die gewijzigd moet worden
 * @return	string					gewijzigde URL
 */
function encodeUrl ($sUrl)
{
	//check if there's an protecol given before the url, if not, add one
	if (preg_match("#(([a-z0-9]{2,}://|mailto:)(.*))#i", $sUrl) == 0)
	{
		$sUrl = "http://" . htmlentities(urlencode($sUrl));
	}
	//TODO: could be tricky, no urlencode anymore!
	return htmlentities(($sUrl));
}


function objToString ($oObj)
{
	ob_start();
	echo $oObj;
	$sContents = ob_get_contents();
	ob_end_clean();
	return $sContents;
}


function loadFileContents ($sFile, $aVars = Array())
{
	extract($aVars, EXTR_REFS);	// Extract the vars to local namespace
	
	ob_start();							// Start output buffering
	include($sFile);					// Include the file
	$sContents = ob_get_contents();		// Get the contents of the buffer
	ob_end_clean();
	return $sContents;
}


function deepImplode ($aArray, $sSeperator = ', ', $sWrapper = 'Array(%s)')
{
	if ($sWrapper == '')
	{
		$sWrapper = "%s";
	}
	$iTotal		= count($aArray);
	$sOutput	= '';
	foreach ($aArray as $mKey => $mValue)
	{
		if (is_array($mValue))			$sOutput .= sprintf($sWrapper, deepImplode($mValue, $sSeperator, $sWrapper));
		elseif (is_string($mValue))		$sOutput .= "'".$mValue."'";
		elseif (is_object($mValue))		$sOutput .= "Object";
		else							$sOutput .= $mValue;
		if (--$iTotal > 0)	$sOutput .= $sSeperator;
	}
	return $sOutput;
}


function language_cols ($aCols, $sLang)
{
	if ($sLang != '')
	{
		array_walk($aCols, 'language_col', $sLang);
	}
	return ' '.implode($aCols, ', ').' ';
}
function language_col (&$sCol, $sKey, $sLang)
{
	$sCol = $sCol.$sLang.' AS '.$sCol;
}


function generate_str ($iLength)
{
	$aRanges = Array(
		Array(97, 122),		// a-z (lowercase)
		Array(65, 90),		// A-Z (uppercase)
		Array(48, 57)		// 0-9 (numeral)
	);
	$sReturn = '';
	
	for ($i = 0; $i < $iLength; $i++)
	{
		//lowercase, uppercase of numeral?
		$iKey		 = mt_rand(0, 2);
		$sReturn	.= chr(mt_rand($aRanges[$iKey][0], $aRanges[$iKey][1]));
	}
	
	return $sReturn;
}


function moneyformat ($fNumber)
{
	return number_format($fNumber, 2, ',', '.');
}


/**
 * Decodeert een hexadecimaal getal naar een ip
 * Elke 2 tekens vormen een onderdeel van het adres. 16*16 = 256 en dus past zo het hoogste ip erin (255.255.255.255)
 *
 * @author	phpbb2.0
 * @param	hexadeci	$hIp		ipadres bestaant uit 8 hexadecimalen
 * @return	string					Hexadecimaal omgezet naar een normaal ipadres
 */
function decode_ip($hIp)
{
	$aRange = explode('.', chunk_split($hIp, 2, '.'));
	return hexdec($aRange[0]). '.' . hexdec($aRange[1]) . '.' . hexdec($aRange[2]) . '.' . hexdec($aRange[3]);
}


/**
 * Encodeert een ip naar een hexadecimaal getal
 *
 * @author	phpbb2.0
 * @param	integer		$iIp		ipadres
 * @return	string					Hexadecimaal ipadres
 */
function encode_ip($sIp)
{
	$aRange = explode('.', $sIp);
	return sprintf("%02x%02x%02x%02x", $aRange[0], $aRange[1], $aRange[2], $aRange[3]);
}


function get_ip ()
{
	return encode_ip($_SERVER['REMOTE_ADDR']);
}


/**
 * gekopieerd van http://nl2.php.net/manual/en/function.array-unshift.php#14358
 */
function array_unshift_assoc(&$aArray, $sKey, $sVal)
{
	$aArray			= array_reverse($aArray, true);
	$aArray[$sKey]	= $sVal;
	$aArray			= array_reverse($aArray, true);
	return count($aArray);
}


function is_logged_in ()
{
	return $_SESSION['user_id'] != GUEST_USER;
}


function create_cookie ($sName, $sValue)
{
	return setcookie($sName, $sValue, time()+36000000, '/'.DIR_PROJECT);
}


function delete_cookie ($sName)
{
	return setcookie($sName, '', 0, '/'.DIR_PROJECT);
}


function trace ($mData = "")
{
	if (!DEBUGGING)		return;
	SOS_Socket::trace($mData);
}

function is_key ($sKey, $aHaystack)
{
	return is_array($aHaystack) && array_key_exists($sKey, $aHaystack);
}

/**
 * Slices off the value associated with the given key
 *
 * @param		Array		$aArray
 * @param		String		$sKey
 * @return		Number		New length, false if operation has failed
 */
function array_key_slice ($aArray, $sKey)
{
	if (!array_key_exists($sKey, $aArray))		return false;
	
	$aKeys		= array_keys($aArray);
	$sPosition	= array_search($sKey, $aKeys);
	
	return array_slice($aArray, $sPosition, 1);
}


/**
* This function creates a thumbnail from an image
* The thumbnail checks for the specified maximum width and height
* Supported: .gif, .jpg, .png
* GD 2.0 library needed!
*
* @author Nebu (Pieter De Schepper)
* @version 1.1
*
* @param string $sImg The location of the image that needs to be resized to a thumbnail
* @param int $iMaxWidth The maximum width of the thumbnail
* @param int $iMaxHeight The maximum hight of the thumbnail
* @param string $sImg The location of the new image (including name of image)
* @return bool
*
*/
function createThumbnail($sImg, $iMaxWidth, $iMaxHeight, $sStore)
{
    //Check if the image exists
    if(!@file_exists($sImg))
    {
        return false;
    }
    
    //Retrieve information of the image
    if(!@$aSize = getimagesize($sImg))
    {
        return false;
    }
    
    //Automatic calculation of maximum height or width
    $dProportion = $aSize[1]/$aSize[0];
    if($iMaxWidth>$aSize[0])
    {
        $iWidth = $iMaxHeight>$aSize[1] ? $aSize[0] : round($iMaxHeight/$dProportion);
        $iHeight = $iMaxHeight>$aSize[1] ? $aSize[1] : $iMaxHeight;
    }
    else if($iMaxWidth<$aSize[0])
    {
        if($iMaxHeight>$aSize[1])
        {
            $iWidth = $iMaxWidth;
            $iHeight = round($iMaxWidth*$dProportion);
        }
        else
        {
            if($dProportion>1)
            {
                $iNewWidth=round($iMaxHeight/$dProportion);
                if($newWidth>$iMaxWidth)
                {
                    $iWidth = $iMaxWidth;
                    $iHeight = round($iMaxWidth*$dProportion);
                }
                else
                {
                    $iWidth = round($iMaxHeight/$dProportion);
                    $iHeight = $iMaxHeight;
                }
            }
            else
            {
                $iNewHeight = round($iMaxWidth*$dProportion);
                if($iNewHeight>$iMaxHeight)
                {
                    $iWidth = round($iMaxHeight/$dProportion);
                    $iHeight = $iMaxHeight;
                }
                else
                {
                    $iWidth = $iMaxWidth;
                    $iHeight = round($iMaxWidth*$dProportion);
                }
            }
        }
    }

    //Create empty image resource for thumbnail
    $rDest = imagecreatetruecolor($iWidth,$iHeight);
    
    //Create image resource from the specified image depending on the format
    switch ($aSize[2])
    {
        case 1: $rSrc=imagecreatefromgif($sImg);break;
        case 2: $rSrc=imagecreatefromjpeg($sImg);break;
        case 3: $rSrc=imagecreatefrompng($sImg);break;
        default: return false;
    }
    
    //Create the thumbnail resource
    $bNoError = imagecopyresampled($rDest, $rSrc, 0, 0, 0, 0, $iWidth, $iHeight, $aSize[0], $aSize[1]);
    
    //Save the thumbnail on the specified location
    if($bNoError)
    {
        switch($aSize[2])
        {
            case 1: $bNoError=imagegif($rDest, $sStore);break;
            case 2: $bNoError=imagejpeg($rDest, $sStore, 100);break;
            case 3: $bNoError=imagepng($rDest, $sStore);break;
        }
    }
    //Return true when the thumbnail is created, false otherwise
    return $bNoError;
}

function getFilename ($sInput)
{
	return preg_replace("/\{\{(.+)\|.+\|.+\}\}/", "\\1", $sInput);
}


?>